class_name LightningMagic
extends Node2D


@onready var animation_player: AnimationPlayer = $AnimationPlayer

@onready var hit_area: Area2D = $HitArea
@onready var collision_shape_2d: CollisionShape2D = $HitArea/CollisionShape2D
var hit_targets: Array = []

var sender: Node2D
var attack: float = 0
var critical_rate: float = 0
var critical_bonus: float = 0
var knockback: float = 0

@export var need_tip: bool = false
@onready var tip_animation_player: AnimationPlayer = $TipAnimationPlayer
@onready var audio_lightning_strike: AudioStreamPlayer2D = $AudioLightningStrike


func _ready() -> void:
	if need_tip:
		tip_animation_player.play("tip")
		await tip_animation_player.animation_finished
		
	audio_lightning_strike.play()
	animation_player.play("lightning")
	var level = get_tree().current_scene as Level
	level.camera.start_shake(7.0, 0.2)
	await animation_player.animation_finished
	queue_free()
	
	
func _physics_process(delta: float) -> void:
	process_hit()


func process_hit():
	if collision_shape_2d.disabled: return
	
	var areas = hit_area.get_overlapping_areas()
	if areas.size() <= 0: return
	
	for area in areas:
		var source = area.source
		if not source in hit_targets:
			hit_targets.append(source)
		
			var hit_data = get_hit_data()
			source.take_hit(hit_data, sender)
			
			
func get_hit_data():
	var is_critical = randf() <= critical_rate
	var critical_attack = attack * (1.0 + critical_bonus)
	
	var hit_data = HitData.new()
	hit_data.is_critical = is_critical
	hit_data.attack = critical_attack if is_critical else attack
	hit_data.knockback = knockback
	
	return hit_data


func set_is_enemy(b: bool):
	hit_area.set_collision_mask_value(5, true)
	if b:
		hit_area.set_collision_mask_value(7, true)
		hit_area.set_collision_mask_value(6, false)
	else:
		hit_area.set_collision_mask_value(7, false)
		hit_area.set_collision_mask_value(6, true)
